package com.petdog.module.recognition.controller;

import com.petdog.common.dto.ApiResponse;
import com.petdog.common.util.FileUploadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 图像上传控制器
 * 提供专门的图像上传API，实现文件格式、大小、分辨率验证等功能
 */
@RestController
@RequestMapping("/api/v1/upload")
public class ImageUploadController {

    private static final Logger logger = LoggerFactory.getLogger(ImageUploadController.class);

    private final FileUploadUtil fileUploadUtil;

    @Autowired
    public ImageUploadController(FileUploadUtil fileUploadUtil) {
        this.fileUploadUtil = fileUploadUtil;
    }

    /**
     * 上传图片文件接口
     * 遵循RESTful API规范，支持文件格式、大小、分辨率验证
     * 
     * @param file 上传的图片文件
     * @return 包含fileId和url的响应
     */
    @PostMapping("/image")
    public ApiResponse<?> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            logger.info("接收到图片上传请求，文件名: {}", file.getOriginalFilename());

            // 调用文件上传工具类进行上传
            String fileUrl = fileUploadUtil.uploadImage(file);

            // 构建成功响应
            String fileId = UUID.randomUUID().toString();
            ImageUploadResponse response = new ImageUploadResponse(
                    fileId,
                    fileUrl,
                    file.getOriginalFilename(),
                    file.getSize(),
                    file.getContentType()
            );

            logger.info("图片上传成功，fileId: {}", fileId);
            return ApiResponse.success(response);

        } catch (IllegalArgumentException e) {
            logger.warn("文件验证失败: {}", e.getMessage());
            if (e.getMessage().contains("文件大小超过限制")) {
                return ApiResponse.error(413, "文件大小超过限制，请压缩后重新上传");
            }
            return ApiResponse.error(400, e.getMessage());

        } catch (IOException e) {
            logger.error("文件上传失败: {}", e.getMessage(), e);
            // 判断是否为网络相关错误
            if (e.getMessage().contains("Connection") || e.getMessage().contains("网络")) {
                return ApiResponse.error(503, "网络连接不稳定，上传失败，请检查网络后重试");
            } else {
                return ApiResponse.error(500, "文件存储失败，请稍后再试");
            }

        } catch (Exception e) {
            logger.error("服务器内部错误: {}", e.getMessage(), e);
            return ApiResponse.error(500, "服务器内部错误，请联系管理员");
        }
    }

    /**
     * 图片上传响应类
     * 封装上传成功后的图片信息
     */
    public static class ImageUploadResponse {
        private String fileId;
        private String url;
        private String originalFilename;
        private long fileSize;
        private String mimeType;

        public ImageUploadResponse(String fileId, String url, String originalFilename, long fileSize, String mimeType) {
            this.fileId = fileId;
            this.url = url;
            this.originalFilename = originalFilename;
            this.fileSize = fileSize;
            this.mimeType = mimeType;
        }

        public String getFileId() {
            return fileId;
        }

        public String getUrl() {
            return url;
        }

        public String getOriginalFilename() {
            return originalFilename;
        }

        public long getFileSize() {
            return fileSize;
        }

        public String getMimeType() {
            return mimeType;
        }
    }
}